/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.oss.cloud;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import io.renren.common.exception.RRException;
import sun.misc.BASE64Decoder;

import javax.management.ObjectName;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.Buffer;

/**
 * 阿里云存储
 *
 * @author Mark sunlightcs@gmail.com
 */
public class AliyunCloudStorageService extends CloudStorageService {
    private OSSClient client;

    public AliyunCloudStorageService(CloudStorageConfig config){
        this.config = config;

        //初始化
        init();
    }

    private void init(){
        client = new OSSClient(config.getAliyunEndPoint(), config.getAliyunAccessKeyId(),
                config.getAliyunAccessKeySecret());
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            client.putObject(config.getAliyunBucketName(), path, inputStream);
        } catch (Exception e){
            throw new RRException("上传文件失败，请检查配置信息", e);
        }

        return config.getAliyunDomain() + "/" + path;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix,File file) {
        return upload(data, getPath(config.getAliyunPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getAliyunPrefix(), suffix));
    }

   /* @Override
    public String downLoad(HttpServletResponse response, String url,String path) {
        String bucketName=config.getAliyunBucketName();
        String objectName=url.replace(config.getAliyunDomain()+"/","");
        String re="";
        try {

            OSSObject ossObject = client.getObject(bucketName, objectName);
            String localPath[]=objectName.split("\\/");
            int len=localPath.length;
            File folder = new File("d:\\"+path);
            if (!folder.exists() && !folder.isDirectory()) {
                folder.mkdirs();
                System.out.println("创建文件夹");
            } else {
                System.out.println("文件夹已存在");
            }
            re="d:\\"+path;
            re=re+"\\"+localPath[len-1];

            File file = new File(re);
            if (!file.exists() && !file.isDirectory()) {
                client.getObject(new GetObjectRequest(bucketName, objectName), new File(re));

            } else {
                System.out.println("文件夹已存在");
            }
// 关闭OSSClient。
            client.shutdown();

        }catch (Exception e){
            e.printStackTrace();
            return "";
        }  return  re;
    }*/

    @Override
    public String downLoad(HttpServletResponse response, String url, String path) {
        ServletOutputStream out;
        String bucketName=config.getAliyunBucketName();
        String objectName=url.replace(config.getAliyunDomain()+"/","");
        String re="";
        String localPath[]=objectName.split("\\/");
        int len=localPath.length;
        re=localPath[len-1];
       try {
           OSSObject ossObject = client.getObject(bucketName, objectName);
           InputStream inputStream=ossObject.getObjectContent();

           out = response.getOutputStream();
           int L=0;
           byte[] buffers=new byte[1024];
           while((L = inputStream.read(buffers)) != -1){
               if (buffers.length!=0){
                   out.write(buffers, 0,L);
               }
           }
           if (client !=null){
               client.shutdown();
           }

           if (out != null) {
               out.flush();
               out.close();
           }
       }catch (Exception e){
           e.printStackTrace();
       }
        return re;
    }

    @Override
    public String uploadFile(File file) {
        return null;
    }
}
